<?php
/**
 * Created by PhpStorm.
 * User: zhang
 * Date: 2018/7/14
 * Time: 15:32
 */

namespace app\account\model;

use app\alipay\model\AddressManager;
use app\alipay\model\ConsumeManager;
use app\common\model\Base;

class BonusPointManager extends UserManager{

    const DB_NAME="bonus_point";

    const BONUS_POINT_EXTRACT_UNPASS = 0;
    const BONUS_POINT_EXTRACT_PASS = 1;
    const BONUS_POINT_EXTRACT_FAIL = 2;
    const BONUS_POINT_EXTRACT_GAIN = 10;

    public function test($uid){
        return $this->getAllBonusPointCountByStatus();
    }
    /*
     *  积分提取
     *  @param integral 提取的积分
     */
    public function setBonusPointExtract($uid, $bonusPoint){

        if(!$this->isValidBonusPoint($uid,$bonusPoint)){
            echoJson(0, "提取积分超过原来积分");
            return;
        }

        if($this->isExistBonusPointOrder($uid)){
            echoJson(0, "积分提取中");
        }

        $bonusPointOrder = array(
            'uid'=>$uid,
            'date'=>date("Y-m-d H:i:sa"),
            'status'=>SELF::BONUS_POINT_EXTRACT_UNPASS,
            'bonus_point'=>$bonusPoint,
            'out_biz_no'=>md5(gettime())
        );

       // echo $this->createIntegralOrderByCustom($integralOrder);
        if($this->setBonusPointExtractByCustom($bonusPointOrder)){
            return true;
        }
     }

    public function setBonusPointGain($uid,$bonusPoint,$subUid){
//        if(!$this->isValidBonusPoint($uid,$bonusPoint)){
//            echoJson(0, "提取积分超过原来积分");
//            return;
//        }

        $bonusPointOrder = array(
            'uid'=>$uid,
            'date'=>date("Y-m-d H:i:sa"),
            'status'=>SELF::BONUS_POINT_EXTRACT_GAIN,
            'bonus_point'=>$bonusPoint,
            'subordinate_id'=>$subUid
        );

        // echo $this->createIntegralOrderByCustom($integralOrder);
        if($this->setBonusPointExtractByCustom($bonusPointOrder)){
            return true;
        }
    }
    //public function acquireIntegral

    public function confirmBonusPointExtract($out_biz_no){
        $BonusPoint = $this->getBonusPointByCustom(array("out_biz_no"=>$out_biz_no));
        $uid = $BonusPoint["uid"];

        if(!$this->isExistBonusPointOrder($uid)){
            echoJson(0, "没有此订单");
        }

        $mAddressManager = new AddressManager();
        $address = $mAddressManager->getAddress($uid);
        //var_dump($address);
        if(empty($address['account'])||empty($address['name'])){
            echoJson(0, "请输入支付宝账号或支付宝姓名");
        }

        //$out_biz_no = md5(gettime());
        return $this->toClient($out_biz_no,$address['account'],$address['name'],$BonusPoint["bonus_point"],$uid);
    }

    public function isValidBonusPoint($uid,$bonusPoint){
        //$this->get
        $userBonusPoint = $this->getBonusPointByUid($uid);
        if($userBonusPoint < $bonusPoint){
            return false;
        }

        return true;
    }

    public function getBonusPointExtractStatusByUid($uid,$status,$page=0){

        if($status == null){
            return $this->getBonusPointListByCustom(array("uid"=>$uid));
        }
        else{
            return $this->getBonusPointListByCustom(array("uid"=>$uid,"status"=>$status));
        }
    }

    public function getAllBonusPointStatusByUid($status=0,$page=0){
        //$gradeSql = "select * from " .SELF::DB_NAME. " where status=0";
        var_dump($status);
        return $this->getBonusPointListByCustom(array("status"=>$status),$page);
    }

    public function getAllBonusPointCountByStatus($status=0){

        return count($this->getBonusPointListByCustom(array('status'=>$status)));
    }

    private function getBonusPointByUid($uid){
        return $this->getUserByCustom(array("uid"=>$uid))["bonus_point"];
    }

    /*
     * @param uid
     * @param date
     * @param status
     * @param bonus_point
     */
    private function setBonusPointExtractByCustom($custom){
        if(empty($custom["subordinate_id"]))
            $createIntegralSql = "INSERT INTO ".self::DB_NAME." (uid,date,status,bonus_point,out_biz_no) VALUES ('".$custom["uid"]."','".$custom["date"]."','".$custom["status"]."','".$custom["bonus_point"]."','".$custom["out_biz_no"]."')";
        else
            $createIntegralSql = "INSERT INTO ".self::DB_NAME." (uid,date,status,bonus_point,subordinate_id,out_biz_no) VALUES ('".$custom["uid"]."','".$custom["date"]."','".$custom["status"]."','".$custom["bonus_point"]."','".$custom["subordinate_id"]."')";

        return $this->mysql->insertSQL($createIntegralSql);
    }

    private function isExistBonusPointOrder($uid){

        if(!$this->getBonusPointByCustom(array("uid"=>$uid,"status"=>0)))
            return false;
        return true;
    }

    private function getBonusPointByCustom($customKey=[]){
        if(count($customKey) == 0){
            $gradeSql = "select * from " .SELF::DB_NAME;
        }else{
            $condition = null;
            foreach ($customKey as $key=>$value){
                //echo "Key: $key; Value: $value<br />\n";
                if($condition==null){
                    $condition = $condition." $key='$value'";
                }else{
                    $condition = $condition." and $key='$value'";
                }

            }

            $gradeSql = "select * from " .SELF::DB_NAME. " where " .$condition;
        }
        $data = $this->mysql->selectSQLRow($gradeSql);
        
        return $data;
    }

    private function getBonusPointListByCustom($customKey=[],$page=0){
        if(count($customKey) == 0){
            $gradeSql = "select * from " .SELF::DB_NAME." LIMIT $page,10";
        }else{
            $condition = null;
            foreach ($customKey as $key=>$value){
                //echo "Key: $key; Value: $value<br />\n";
                if($condition==null){
                    $condition = $condition." $key='$value'";
                }else{
                    $condition = $condition." and $key='$value'";
                }

            }

            $gradeSql = "select * from " .SELF::DB_NAME. " where " .$condition." LIMIT $page,10";
        }
        $data = $this->mysql->selectSQLAll($gradeSql);

        return $data;
    }

    private function toClient($out_biz_no,$payee_account,$payee_name,$amount,$uid){
        include EXTEND_PATH.'alipay-sdk/AopSdk.php';

        $aop = new \AopClient();
        $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
        $aop->appId = "2018053160282375";
        $aop->rsaPrivateKey = 'MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQDmn4YP9XmbFToB/vghSCsnv0ro52zgpeAfkqTnG7XFhnTdGvPDVuOjXaoDR9kIBOa1U2TfdV728MqoZCqAZSAJ+rw28+StL8y3x+thn5rf2j7jb5oXu9kMlMh5FHGaU8tVwgrEG12krEiquH5D9hn57OGlk3LvvTAZyNOkMQxxIkzBH2hnPtjax8upaAOOj4MZ3QckNlAjOglqQDBWOPiU7EE0KXwxW6h3pHEz8WPBI+nh3X1UpFCClmZaPGLLLTvPletfPWCYpFc3d6YMMiMhmES5z/MO9pLOjp3grBXN+A67hG805Xsk/CPEcbUsJv/usvkCcYR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B3XTnPQdx76E+lBdiRbuvkjx5XJVEB5NoUsOLRpg0lyhNNLNqB5BwjVpYbF29fyLUdaLYsz82Vxbg+SeaQfI9hAFjmgho7kCgrcH8tphK7MXAR77gXMZXMILnhdM3qM6pM3R/RnQrGiHOaQgVL9/mMtcjeB1yBgXQpoeBPf0g4GA==';
        $aop->alipayrsaPublicKey = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqi7sVmCL+Xd1zyX99QOlwEws7pXXusEnv939YU7sGGELL7rx99n5+8oYjaN/CkY5QTmp5mre59QoQl51eqcySnSlHknJpyE4xcudqAq/ons2QVdFlw6oJzjMrcEowUPSWNZA3ENlOCVQNYGY4cupM1fLmX5pye5PCXKMth5Ka+Ju9dO4k07SSZJV+uc6O+/nv/b2686Xyf95sRqJcJKcQyq7m8fYWRSQpVNVgv1AErSmJCvMCJblOV0g5apQfC16KooQYRy9sm95kCggt2+dqUSxFJivNtvSTxY1z3URzoWUlqdGjCJQ0FPs5QvtNX2XRkEStN0bWdhzjUcRlmvEkQIDAQAB';
        $aop->apiVersion = '1.0';
        $aop->signType = 'RSA2';
        $aop->postCharset='UTF-8';
        $aop->format='json';
        $request = new \AlipayFundTransToaccountTransferRequest();


        $request->setBizContent("{" .
            "\"out_biz_no\":\"".$out_biz_no."\"," .
            "\"payee_type\":\"ALIPAY_LOGONID\"," .
            "\"payee_account\":\"".$payee_account."\"," .
            "\"amount\":\"".$amount."\"," .
            "\"payer_show_name\":\"上医道元-积分提取成功\"," .
            "\"payee_real_name\":\"".$payee_name."\"," .
            "\"remark\":\"转账备注\"" .
            "}");
        $result = $aop->execute ( $request);

        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        $resultCode = $result->$responseNode->code;

        if(!empty($resultCode)&&$resultCode == 10000){
            $consume = new ConsumeManager();
            $consume->updateUserBonusPoint($uid, $amount, ConsumeManager::COST_PLUS);
            $this->updateBonusPointStatus($out_biz_no, self::BONUS_POINT_EXTRACT_PASS,"");
            return true;
        } else {
            $this->updateBonusPointStatus($out_biz_no, self::BONUS_POINT_EXTRACT_FAIL,$result->$responseNode->sub_msg);
            echoJson(0, $result->$responseNode->sub_msg);
            return false;
        }
    }

    private function updateBonusPointStatus($out_biz_no,$status,$msg){
        $this->updateBonusPointOrderByCustom(array('out_biz_no'=>$out_biz_no),array("status"=>$status,"msg"=>$msg));
    }

    protected function updateBonusPointOrderByCustom($saveCondition,$saveSequence=[]){
        $conditionSql = null;
        $SequencceSql = null;
        foreach ($saveCondition as $key=>$value){
            //echo "Key: $key; Value: $value<br />\n";
            if($conditionSql==null){
                $conditionSql = $conditionSql."$key='$value'";
            }else{
                $conditionSql = $conditionSql." and $key='$value'";
            }
        }

        foreach ($saveSequence as $key=>$value){
            //echo "Key: $key; Value: $value<br />\n";
            if($SequencceSql==null){
                $SequencceSql = $SequencceSql."$key='$value'";
            }else{
                $SequencceSql = $SequencceSql.",$key='$value'";
            }
        }

        $orderSql = "update " .SELF::DB_NAME. " set ".$SequencceSql." where " .$conditionSql;

        return $this->mysql->updateSQL($orderSql);
    }
}
